package pe.edu.unmsm.pacis.shca.ams.agent;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import pe.edu.unmsm.pacis.shca.domain.message.GlobalMessage;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;

public class DemoAgent extends Agent {
	
	private static final long serialVersionUID = 1L;

	protected void setup() {

		// pong behaviour
		addBehaviour(new CyclicBehaviour(this) {
			public void action() {
				ACLMessage msg = receive();
				String content = "";
				GlobalMessage recep = null;
				if (msg != null) {
					System.out.println("");
					try {
						System.out.println(":::::::::::: Recived: " + msg.getContentObject());
						recep = (GlobalMessage)msg.getContentObject();
						Map map = recep.getSend();
						Iterator itr = map.entrySet().iterator();
						while (itr.hasNext()) {
							Map.Entry e = (Map.Entry)itr.next();
							System.out.println("  Key: "+e.getKey()+"   Value:"+e.getValue());
						}
					} catch (UnreadableException e) {
						//e.printStackTrace();
					}
					
					content = ":: LocalName:" + myAgent.getLocalName() + " - Name:" + myAgent.getName() + " - sent: " + "Process done !!!";
					
					ACLMessage reply = msg.createReply();
					reply.setPerformative(ACLMessage.INFORM);
					reply.setContent(content);
					/*
					try {
						reply.setContentObject(recep);
					} catch (IOException e) {	
						e.printStackTrace();
					}*/
					send(reply);
					System.out.println(content);
					System.out.println("Finally");
				} else
					block();
			}
		});

	}

	protected void takeDown() {
		try {
			DFService.deregister(this);
		} catch (Exception e) {
		}
	}
}
